Page({
  data: {
    ctx:null,
    canvas:null,
    width: 300,
    height: 150,
    scanning:false,
    renderList:[],
    scaleTime:0.2, // 百分比
    imgsList:[],
  },
  onReady(){
    const query = wx.createSelectorQuery();
    const t =this,d = t.data;
    query.select('#myCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        d.canvas = res[0].node
        d.ctx = d.canvas.getContext('2d');
        console.log(d.ctx)
        t.loadImages()
      })
  },
  loadImages() {
    const t = this,d = t.data;
    const images = [
      '/cheng/images/bg1.png',
      '/cheng/images/bg2.png',
      '/cheng/images/bg3.png',
      '/cheng/images/bg4.png',
      '/cheng/images/bg5.png',
    ];
    images.forEach((src) => {
      let img = d.canvas.createImage();
      img.src = src;
      img.onload = function() {
        d.imgsList.push(img);
      }
    });
  },
  getRandom(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1))
  },
  createRender(){
    const t = this,d = t.data;
    if (d.imgsList.length == 0) return null;
    const basicScale = [0.6, 0.9, 1.2][t.getRandom(0, 2)];
    const image = d.imgsList[t.getRandom(0, d.imgsList.length - 1)]
    const offset = 0;
    const basicX = d.width / 2 + t.getRandom(-offset, offset);
    const angle = t.getRandom(2, 10);
    let ratio = t.getRandom(10, 30) * ((t.getRandom(0, 1) ? 1 : -1));
    const fadeOutStage = t.getRandom(14, 18) / 100;


    const getScale = (diffTime) => {
      if (diffTime < d.scaleTime) {
        return +((diffTime / d.scaleTime).toFixed(2)) * basicScale;
      } else {
        return basicScale;
      }
    };
    const getTranslateX = (diffTime) => {
      if (diffTime < d.scaleTime) { // 放大期间，不进行摇摆位移
        return basicX;
      } else {
        return basicX + ratio * Math.sin(angle * (diffTime - d.scaleTime));
      }
    };
    const getTranslateY = (diffTime) => {
      return image.height / 2 + (d.height - image.height / 2) * (1 - diffTime);
    };
    const getAlpha = (diffTime) => {
      let left = 1 - +diffTime;
      if (left > fadeOutStage) {
        return 1;
      } else {
        return 1 - +((fadeOutStage - left) / fadeOutStage).toFixed(2);
      }
    };
    return (diffTime) => {
      // 差值满了，即结束了 0 ---》 1
      if (diffTime >= 1) return true;
      d.ctx.save();
      const scale = getScale(diffTime);
      // const rotate = getRotate();
      const translateX = getTranslateX(diffTime);
      const translateY = getTranslateY(diffTime);
      d.ctx.translate(translateX, translateY);
      d.ctx.scale(scale, scale);
      // context.rotate(rotate * Math.PI / 180);
      d.ctx.globalAlpha = getAlpha(diffTime);
      d.ctx.drawImage(
        image,
        -image.width / 2, -image.height / 2,
        image.width, image.height,
      );
      console.log(scale,translateX,translateY)
      d.ctx.restore();
    };
  },
  /**
   * CanvasContext.drawImage(
   * string imageResource, 路径
   * number sx, number sy, 起始位置
   * number sWidth, number sHeight, 宽高
   * number dx, number dy,
   * number dWidth, number dHeight
   * )
   */
  scan() {
    const t= this, d = t.data;
    d.ctx.clearRect(0, 0, d.width, d.height);
    d.ctx.fillStyle = "#f4f4f4";
    d.ctx.fillRect(0, 0, d.width, d.height);
    let index = 0;
    let length = d.renderList.length;
    if (length > 0) {
      t.requestFrame(t.scan.bind(t));
      d.scanning = true;
    } else {
      d.scanning = false;
    }
    while (index < length) {
      const child = d.renderList[index];
      if (!child || !child.render || child.render.call(null, (Date.now() - child.timestamp) / child.duration)) {
        // 结束了，删除该动画
        d.renderList.splice(index, 1);
        length--;
      } else {
        // continue
        index++;
      }
    }
  },
  start() {
    const t = this, d = t.data;
    const render = t.createRender();
    const duration = t.getRandom(1500, 3000);
    d.renderList.push({
      render,
      duration,
      timestamp: Date.now(),
    });
    if (!d.scanning) {
      d.scanning = true;
      t.requestFrame(t.scan.bind(t));
    }
    return t;
  },

  requestFrame(cb) {
    let d = this.data;
    return (
      d.ctx.requestAnimationFrame ||
      function(callback) {
        setTimeout(callback, 1000 / 60);
      }
    )(cb);
  },
})
